package net.jiug.email.handle;

import net.jiug.common.config.ConfigEmail;
import net.jiug.common.utils.EmailUtils;
import net.jiug.common.utils.ValidationUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/send")
public class EmailServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 安全检查
        String key = request.getParameter("key");
        if(key==null||!ConfigEmail.secretKey.contains(key)){
            response.getWriter().write("key check fail");
            return;
        }

        // 目的邮箱
        String toEmail = request.getParameter("toEmail");
        // 目的邮箱检查
        if (!ValidationUtil.isEmail(toEmail)) {
            response.getWriter().write("email check fail");
            return;
        }

        // 邮件标题处理
        String title = request.getParameter("title");
        if (ValidationUtil.isEmpty(title)) {
            title = ConfigEmail.noticeTitle;
        }

        // 邮件类型获取
        String type = request.getParameter("type");
        if (ValidationUtil.isEmpty(type)) {
            type = "0";
        }

        // 邮件内容处理
        String content = request.getParameter("content");
        String note = request.getParameter("note");
        switch (type) {
            // 1：简易验证码
            case "1":
                content = "您的验证码是：" + content
                        + "，此验证码用于" + note
                        + "，若非本人操作，请忽略此邮件。";
                break;
            // 2：标签+内容
            case "2":
                content = note + content;
                break;
                // 默认：内容不处理
        }

        // 发送邮件
        try {
            EmailUtils.sendEmail(toEmail, title, content);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("send fail");
            return;
        }

        // 尝试更新会话
        tryUpdateSession();

        response.getWriter().write("ok");
    }

    private static void tryUpdateSession() {
        // 使用次数到达使用阈值时进行更新
        if(ConfigEmail.emailUseThresholdValue<=++EmailUtils.currentUseCount){
            // 使用次数重置
            EmailUtils.currentUseCount=0;
            // 当前使用邮箱序号++/0
            if(ConfigEmail.emailList.size()<=++EmailUtils.currentUseEmailIndex)
                EmailUtils.currentUseEmailIndex=0;
            // 更新邮箱会话连接
            EmailUtils.updateSession();
        }
    }

}


/*

    protected static final Logger logger = Logger.getLogger(BaseController.class.getName());

    @Resource
    protected ConfigSecretKey configSecretKey;

    protected void securityVerification(String uuid) throws Exception{
        Set<String> requestSecretKey = configSecretKey.getRequestSet();
        if(!requestSecretKey.contains(uuid)){
            String errorMessage = "uuid不存在";
            logger.severe(errorMessage);
            throw new BadRequestException(errorMessage);
        }
    }
@RequestMapping("/send/{uuid}")
@ResponseBody
public ResponseEntity<Object> send(@PathVariable("uuid") String uuid, @RequestBody EmailContent emailContent) {
    try {
        // 安全检查
        securityVerification(uuid);
        // 业务逻辑
        emailService.notice(emailContent);
    } catch (BadRequestException e) {
        return new ResponseEntity<>(e.getMessage(),HttpStatus.BAD_REQUEST);
    } catch (Exception e) {
        logger.log(Level.SEVERE,
                "An error occurred on line " + e.getStackTrace()[0].getLineNumber() + ": " + e.getMessage(), e);
        return new ResponseEntity<>(e.getMessage(),HttpStatus.INTERNAL_SERVER_ERROR);
    }
    return new ResponseEntity<>(HttpStatus.OK);
}
 */